import { Injectable } from '@nestjs/common';

@Injectable()
export class UtilsService {
    successRes(data:any = null, params?:{[key : string] : any}, msg?:string) {
        let result:{[key : string] : any} = {
            success : true,
            data : null,
            msg : msg,
            code : 0
        }
    
        if(data !== null) {
            result.data = data
        }
    
        if(params) {
            result = Object.assign(result, params)
        }
    
        return result
        
    }
    
    failRes(msg?:string, params?:{[key : string] : any}) {
        let result:{[key : string] : any} = {
            success : false,
            data : null,
            msg : msg,
            code : 0
        }
    
        if(msg !== undefined) {
            result.msg = msg
        }
    
        if(params) {
            result = Object.assign(result, params)
        }
    
        return result
        
    }

    time(date?:string|number|Date) {
        return Math.floor(Date.now() / 1000)
    }

    maskPhoneNumber(phoneNumber) {
        return phoneNumber.replace(/(\d{3})\d*(\d{4})/, "$1****$2");
    }

    isWithinTimeRange(timestamp:number|Date, timeRange:string[]) {
        const date = typeof timestamp == 'number' ? new Date(timestamp * 1000) : timestamp
        const hours = date.getHours();
        const minutes = date.getMinutes();
        const time = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
      
        if (time >= timeRange[0] && time < timeRange[1]) {
          return true;
        }
        return false;
    }

    round(num:number|string, digits = 2) {
        num = String(num)
        const nums = num.split('.')
        if(nums.length == 1) {
            return Number(num)
        }else {
            return Number(nums[0] + '.' + nums[1].substring(0, digits))
        }
    }
}
